#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This module lets you monitor CherryPy threads at /cpstatus.
To enable this, add these lines to your run_webpyte.py:

status = loader.config_app(app_module="webpyte.status", mountpoint="/cpstatus",
                           packages=(), use_routes=False, use_auth=False)
"""

import threading, time, cherrypy

class ThreadStatus(object):
    number = 0
    
    def __init__(self, id):
        self.start = None
        self.end = None
        self.url = None
        self.id = id
        ThreadStatus.number += 1
        self.number = ThreadStatus.number
        # print "NNNNNNNNNNNNNNNN", self.number
    
    def last_req_time(self):
        if self.end is None:
            return 0
        return self.end - self.start
    
    def idle_time(self):
        if self.end is None:
            return 0
        return time.time() - self.end
    
    def __cmp__(self, other):
        return cmp(self.number, other.number)
        #return cmp(self.id, other.id)



class StatusMonitor(cherrypy.Tool):
    """Registers the status of each thread."""
    
    def __init__(self):
        self._point = 'on_start_resource'
        self._name = 'status'
        self._priority = 50
        self.seen_threads = {}
    
    def callable(self):
        threadID = threading._get_ident()
        ts = self.seen_threads.get(threadID, None)
        if not ts:
            ts = ThreadStatus(threadID)
            self.seen_threads[threadID] = ts
        ts.start = cherrypy.response.time
        ts.url = cherrypy.url()
        ts.end = None
    
    def unregister(self):
        """Unregister the current thread."""
        threadID = threading._get_ident()
        if threadID in self.seen_threads:
            self.seen_threads[threadID].end = time.time()
    
    def _setup(self):
        cherrypy.Tool._setup(self)
        cherrypy.request.hooks.attach('on_end_resource', self.unregister)

cherrypy.tools.status = StatusMonitor()



from webpyte import Loader
from gensher import page, gensher

class Root(object):
    def ps(self):
        import os, subprocess
        pid = os.getpid()
        cmd = "ps aux | grep %s | grep -v grep" % pid
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        dump = p.stdout.readline()
        l = dump.split()
        return dict(user=l[0], pid=l[1], cpu=l[2], mem=l[3],
                    virtual_mem=l[4], memory=l[5], command=" ".join(l[10:]))
    
    @cherrypy.expose()
    @page("cpstatus.html")
    def index(self):
        threads = cherrypy.tools.status.seen_threads.values()
        threads.sort()
        return dict(pagetitle="CherryPy Status",
                    threads=threads,
                    proc=self.ps())
    
    @cherrypy.expose()
    def delay(self, secs):
        # Help demo last_req_time (since my box returns index in under 1 msec).
        time.sleep(float(secs))
        return self.index()


cherrypy.config.update({"tools.status.on": True})
